﻿using B.S.RbacData.ErrorCode;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys;
using MediatR;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.Traceabilitys
{
    /// <summary>
    /// 上传文件的命令处理
    /// </summary>
    public class UpFilesCommandhandlter : IRequestHandler<UpFilesCommand, ApiResult<string>>
    {
        /// <summary>
        /// 网络主机环境
        /// </summary>
        private readonly IWebHostEnvironment web;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="web">网络主机环境</param>
        public UpFilesCommandhandlter(IWebHostEnvironment web)
        {
            this.web = web;
        }


        public async Task<ApiResult<string>> Handle(UpFilesCommand request, CancellationToken cancellationToken)
        {

            //获取根目录
            var root = web.WebRootPath;
            var id = Guid.NewGuid();
            //物理路径
            var newname = @"\Imgs\" + id + request.file.FileName;
            var path = root + newname;
            //创建文件流保存
            using (FileStream df = System.IO.File.Create(path))
            {

                request.file.CopyTo(df);
                df.Close();

            }

            return new ApiResult<string>()
            {
                code = ResultEnumCode.Ok,
                message = "上传成功",
                data = "/Imgs/" + id + request.file.FileName //返回虚拟路径

            };

        }
    }
}
